package com.content.management.biz.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.content.management.biz.ClassificationManageService;
import com.content.management.domain.dto.ClassificationAddDto;
import com.content.management.domain.dto.SummaryByClassificationDto;
import com.content.management.domain.entity.DictionaryData;
import com.content.management.domain.query.ClassificationQuery;
import com.content.management.domain.vo.ClassificationVo;
import com.content.management.service.BusPublishContentService;
import com.content.management.service.DictionaryDataService;
import com.content.management.util.enums.DirectoryFlag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xinghu
 * @version 1.0
 * @date 2020/4/4 5:58 下午
 */
@Slf4j
@Service
@AllArgsConstructor
public class ClassificationManageServiceImpl implements ClassificationManageService {

	private final BusPublishContentService publishContentService;

	private final DictionaryDataService dictionaryDataService;

	@Override
	public IPage<ClassificationVo> voPage(ClassificationQuery query) {
		IPage<DictionaryData> page = dictionaryDataService.lambdaQuery()
				.eq(DictionaryData::getDirectoryFlag, DirectoryFlag.CLASSIFICATION_FLAG.getFlag())
				.like(StringUtils.isNotBlank(query.getClassification()), DictionaryData::getDictionaryData, query.getClassification())
				.page(new Page<>(query.getCurrent(), query.getSize()));
		List<String> classificationLis = page.getRecords().stream().map(DictionaryData::getDictionaryFlag).collect(Collectors.toList());
		List<SummaryByClassificationDto> dtoList = publishContentService.summaryByClassification(classificationLis);
		Map<String, SummaryByClassificationDto> dtoMap = dtoList.stream().collect(Collectors.toMap(SummaryByClassificationDto::getClassification, Function.identity()));
		return page.convert(item -> ClassificationVo.of(item, dtoMap));
	}

	@Override
	public boolean deleteById(Long id) {
		return dictionaryDataService.removeById(id);
	}

	@Override
	public boolean saveOrUpdateClassification(ClassificationAddDto dto) {
		DictionaryData data = dto.to();
		data.setDirectoryFlag(DirectoryFlag.CLASSIFICATION_FLAG.getFlag());
		return dictionaryDataService.saveOrUpdate(data);
	}
}
